package com.ecp.commons.listener;

import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ecp.commons.Environment;

public class EnvironmentListener implements ServletContextListener {

	private Log	log	= LogFactory.getLog(EnvironmentListener.class);

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		log.info("Init environment.");
		try {
			ServletContext context = sce.getServletContext();
			Environment env = Environment.getEnv();

			Enumeration<?> contextEnumeration = context.getInitParameterNames();
			while (contextEnumeration.hasMoreElements()) {
				String attrName = (String) contextEnumeration.nextElement();
				env.setAttribute(attrName, context.getInitParameter(attrName));
			}

			String realPath = sce.getServletContext().getRealPath("/");
			env.setAttribute("WebAppPath", realPath);
			env.setAttribute("RealUploadPath", context.getRealPath((String) env.getAttribute("UploadPath")));

			/*
			if (env.getAttribute("ContextPath") == null) {
				synchronized (env) {
					String ctxPath = ((HttpServletRequest) request).getContextPath();
					env.setAttribute("ContextPath", ctxPath);
				}
			}*/

			// IndexerManager manager = (IndexerManager) env.getBean("FullTextIndexerManager");
			// manager.init();

			env.initialize();

			log.info("Environment initialized.");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

}